package com.idanchuang.support.etcache.pubsub.redis;

import com.idanchuang.support.etcache.pubsub.AbstractRemoteEventSubscriber;
import com.idanchuang.support.etcache.pubsub.SubEventQueue;
import com.idanchuang.support.etcache.remote.codec.RemoteKeyCodec;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.nio.charset.StandardCharsets;

/**
 * 基于Redis Lettuce实现的缓存变更事件监听器
 * @author yjy
 * Created at 2021/12/22 12:44 下午
 */
public class RedisRemoteEventSubscriber extends AbstractRemoteEventSubscriber implements MessageListener {

    private final RedisConnection connection;

    public RedisRemoteEventSubscriber(RemoteKeyCodec remoteKeyCodec, SubEventQueue subEventQueue,
                                      String appId, RedisConnectionFactory redisConnectionFactory) {
        super(remoteKeyCodec, subEventQueue);
        String cs = "etcache-event-" + appId.toLowerCase();
        byte[] channel = cs.getBytes(StandardCharsets.UTF_8);
        this.connection = redisConnectionFactory.getConnection();
        this.connection.subscribe(this, channel);
    }

    @Override
    public void destroy() {
        if (this.connection != null && !this.connection.isClosed()) {
            this.connection.close();
        }
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        handle(message.getBody());
    }

}
